import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:custom_refresh_indicator/custom_refresh_indicator.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:insta_image_viewer/insta_image_viewer.dart';
import 'package:school_assistant/common_colors.dart';
import 'package:school_assistant/shop_page.dart';
import 'package:school_assistant/toast_utils.dart';
import 'package:school_assistant/user_feedback_imgs.dart';
import 'package:sp_util/sp_util.dart';

import 'article_detail.dart';
import 'common_client.dart';
import 'common_utils.dart';
import 'data/article_entity.dart';
import 'data/article_extra_entity.dart';
import 'hospital_page.dart';

class HallPage extends StatefulWidget {
  const HallPage({Key? key}) : super(key: key);

  @override
  State<HallPage> createState() => _HallPageState();
}

class _HallPageState extends State<HallPage> {
  var news = [
    [
      "https://n.sinaimg.cn/news/transform/13/w500h313/20230420/bccb-eec8c4d27f5ebc6e4bfc243d1477db7d.jpg",
      "https://news.sina.com.cn/gov/xlxw/2023-04-20/doc-imyqzcvq9822261.shtml"
    ],
    [
      "https://n.sinaimg.cn/default/transform/400/w240h160/20230420/6de5-9c1e1ed044c4247b4536ea632dfda6a5.jpg",
      "https://news.sina.com.cn/gov/xlxw/2023-04-20/doc-imyqzkck0088240.shtml"
    ],
    [
      "https://n.sinaimg.cn/spider20230419/660/w936h524/20230419/cc0f-decaeeddc870f21e22062d957d1db35d.png",
      "https://news.sina.com.cn/gov/xlxw/2023-04-20/doc-imyqxmni7944880.shtml"
    ],
    [
      "https://n.sinaimg.cn/news/transform/400/w240h160/20230420/55ff-881b24029ff939cf50552d2d1f571c28.jpg",
      "https://news.sina.com.cn/gov/xlxw/2023-04-20/doc-imyqyxpv5105467.shtml"
    ],
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xfff1f1f1),
        body: CustomRefreshIndicator(
          child: ListView.builder(
              itemCount: 2 + articles.length,
              itemBuilder: (BuildContext context, int index) => _item(index)),
          builder: MaterialIndicatorDelegate(
            builder: (context, controller) {
              return Icon(
                Icons.ac_unit,
                color: Colors.blue,
                size: 30,
              );
            },
          ),
          onRefresh: myAsyncRefreshFunction,
        ));
  }

  @override
  void initState() {
    super.initState();
    _getArticle();
  }

  List<ArticleEntity> articles = [];

  _getArticle() async {
    try {
      var res = await CommonClient().getArticleAll(1, 100);
      List<dynamic> data = jsonDecode(res.data ?? "");
      List<ArticleEntity> gs = [];
      if (data != null) {
        data.forEach((element) {
          gs.add(ArticleEntity.fromJson(element));
        });
      }
      setState(() {
        articles.clear();
        articles.addAll(gs);
      });
      print(gs);
    } catch (e) {
      print(e);
    }
  }

  _like(String article) async {
    try {
      List<String> likes = [];
      try {
        var likeStr = SpUtil.getString("likeA") ?? '[]';
        List<dynamic> likeList = jsonDecode(likeStr);
        for (var element in likeList) {
          likes.add(element.toString());
        }
      } catch (e) {
        print(e);
      }
      if (likes.contains(article)) {
        var res =
            await CommonClient().unlike(SpUtil.getString("uid") ?? '', article);
        likes.remove(article);
      } else {
        var res =
            await CommonClient().like(SpUtil.getString("uid") ?? '', article);
        likes.add(article);
      }
      SpUtil.putString("likeA", jsonEncode(likes));
      _getArticle();
    } catch (e) {
      print(e);
    }
  }

  _item(int index) {
    if (index == 0) {
      // return Container(height: 200, color: Colors.black);
      return Container(
        height: 160,
        child: Swiper(
          itemBuilder: (BuildContext context, int index) {
            return GestureDetector(
              onTap: () {
                Get.to(HospitalPage(news[index][1]));
              },
              child: CachedNetworkImage(
                fit: BoxFit.fitWidth,
                alignment: Alignment.topCenter,
                imageUrl: news[index][0],
              ),
            );
          },
          itemCount: news.length,
          viewportFraction: 0.8,
          autoplay: true,
          scale: 0.9,
        ),
      );
    } else if (index == 1) {
      // return Container(
      //   height: 100,
      //   margin: EdgeInsets.only(left: 12, right: 12, top: 12),
      //   decoration: BoxDecoration(
      //       borderRadius: BorderRadius.circular(8), color: Colors.white),
      //   child: Row(
      //     children: [
      //       // Expanded(
      //       //     flex: 1,
      //       //     child: GestureDetector(
      //       //       onTap: () {},
      //       //       child: Column(
      //       //         mainAxisAlignment: MainAxisAlignment.center,
      //       //         children: [
      //       //           Image.asset(
      //       //             'images/ic_shiwu.png',
      //       //             width: 40,
      //       //             height: 40,
      //       //           ),
      //       //           SizedBox(
      //       //             height: 10,
      //       //           ),
      //       //           Text(
      //       //             "失物招领",
      //       //             style:
      //       //                 TextStyle(color: Color(0xff333333), fontSize: 13),
      //       //           )
      //       //         ],
      //       //       ),
      //       //     )),
      //       Expanded(
      //           flex: 1,
      //           child: GestureDetector(
      //             onTap: () {
      //               Get.to(ShopPage());
      //             },
      //             child: Column(
      //               mainAxisAlignment: MainAxisAlignment.center,
      //               children: [
      //                 Image.asset(
      //                   'images/ic_diancai.png',
      //                   width: 40,
      //                   height: 40,
      //                 ),
      //                 SizedBox(
      //                   height: 10,
      //                 ),
      //                 Text(
      //                   '食堂点单',
      //                   style:
      //                       TextStyle(color: Color(0xff333333), fontSize: 13),
      //                 )
      //               ],
      //             ),
      //           )),
      //       Expanded(
      //           flex: 1,
      //           child: GestureDetector(
      //             onTap: () {
      //               Get.to(HospitalPage(''));
      //             },
      //             child: Column(
      //               mainAxisAlignment: MainAxisAlignment.center,
      //               children: [
      //                 Image.asset(
      //                   UserFeedBackImgs.hospital,
      //                   width: 40,
      //                   height: 40,
      //                 ),
      //                 SizedBox(
      //                   height: 10,
      //                 ),
      //                 Text(
      //                   '医疗百科',
      //                   style:
      //                       TextStyle(color: Color(0xff333333), fontSize: 13),
      //                 )
      //               ],
      //             ),
      //           )),
      //       // Expanded(
      //       //     flex: 1,
      //       //     child: GestureDetector(
      //       //       onTap: () {
      //       //         Get.to(ShopPage());
      //       //       },
      //       //       child: Column(
      //       //         mainAxisAlignment: MainAxisAlignment.center,
      //       //         children: [
      //       //           Image.asset(
      //       //             'images/ic_diancai.png',
      //       //             width: 40,
      //       //             height: 40,
      //       //           ),
      //       //           SizedBox(
      //       //             height: 10,
      //       //           ),
      //       //           Text(
      //       //             '功能4',
      //       //             style:
      //       //                 TextStyle(color: Color(0xff333333), fontSize: 13),
      //       //           )
      //       //         ],
      //       //       ),
      //       //     )),
      //     ],
      //   ),
      // );
      return Container();
    } else {
      var articleEntity = articles[index - 2];
      ArticleExtraEntity? extra;
      List<dynamic> imgs = jsonDecode(articleEntity.image ?? '');
      if (articleEntity.extra?.isNotEmpty == true) {
        extra =
            ArticleExtraEntity.fromJson(jsonDecode(articleEntity.extra ?? ''));
      }

      List<dynamic>? comments =[];
      try {
        comments= jsonDecode(extra?.comment ?? '');
      } catch (e) {
        print(e);
      }
      return GestureDetector(
        child: Container(
          margin: EdgeInsets.only(left: 12, right: 12, top: 12),
          padding: EdgeInsets.all(12),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(4)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Row(
                children: [
                  CachedNetworkImage(
                      imageBuilder: (context, image) => CircleAvatar(
                            backgroundImage: image,
                          ),
                      errorWidget: (context, url, error) => CircleAvatar(
                            backgroundImage:
                                AssetImage(UserFeedBackImgs.user_male),
                          ),
                      width: 50,
                      height: 50,
                      imageUrl: UserFeedBackImgs.url + (extra?.profile ?? '')),
                  SizedBox(
                    width: 12,
                  ),
                  RichText(
                      text: TextSpan(children: [
                    TextSpan(
                        text: (extra?.username ?? "姓名") + "\n",
                        style: TextStyle(
                            color: Color(0XFF333333), fontSize: 13, height: 2)),
                    TextSpan(
                        text: extra?.time ?? "2202-10-11",
                        style: TextStyle(
                            color: Color(0XFF333333), height: 2, fontSize: 13))
                  ]))
                ],
              ),
              Container(
                padding: EdgeInsets.all(6),
                margin: EdgeInsets.only(top: 6),
                decoration: BoxDecoration(
                    color: Color(0XFFF1F1F1),
                    borderRadius: BorderRadius.circular(4)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(articleEntity.title ?? "",
                        style: TextStyle(
                            color: Color(0XFF333333),
                            fontSize: 15,
                            fontWeight: FontWeight.w600)),
                    SizedBox(
                      height: 4,
                    ),
                    Text(articleEntity.body ?? "",
                        style: TextStyle(
                          color: Color(0XFF666666),
                          fontSize: 14,
                        )),
                    SizedBox(
                      height: 4,
                    ),
                    // RichText(
                    //     text: TextSpan(children: [
                    //   TextSpan(
                    //       text: "请通过",
                    //       style: TextStyle(
                    //         color: Color(0XFF666666),
                    //         fontSize: 13,
                    //       )),
                    //   TextSpan(
                    //       text: extra?.contract ?? "1222202-10-11",
                    //       style: TextStyle(
                    //           color: Color(0XFF333333),
                    //           fontWeight: FontWeight.w600,
                    //           fontSize: 13)),
                    //   TextSpan(
                    //       text: "联系我，或者前往",
                    //       style: TextStyle(
                    //           color: Color(0XFF666666), fontSize: 13)),
                    //   TextSpan(
                    //       text: extra?.loc ?? "1222202-10-11",
                    //       style: TextStyle(
                    //           color: Color(0XFF333333),
                    //           fontWeight: FontWeight.w600,
                    //           fontSize: 13)),
                    // ])),
                    SizedBox(
                      height: 10,
                    ),
                    GridView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        childAspectRatio: 1,
                        crossAxisSpacing: 10,
                      ),
                      itemCount: imgs.length,
                      itemBuilder: (context, index) {
                        //   return Image.file(File(imgAD[index].path));
                        return _singleAD(UserFeedBackImgs.url + imgs[index]);
                      },
                    ),
                    SizedBox(
                      height: 10,
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 12,
              ),
              Row(
                children: [
                  SizedBox(
                    width: 20,
                  ),
                  Icon(
                    Icons.comment,
                    color: CommonColor.color99,
                    size: 20,
                  ),
                  SizedBox(
                    width: 6,
                  ),
                  Text((comments?.length ?? 0).toString()),
                  Spacer(),
                  GestureDetector(
                    child: Icon(
                      Icons.favorite,
                      color: QUtils.localLike(articleEntity.id ?? '')
                          ? Colors.red
                          : CommonColor.color99,
                      size: 20,
                    ),
                    onTap: () => _like(articleEntity.id ?? ''),
                  ),
                  SizedBox(
                    width: 6,
                  ),
                  GestureDetector(
                    child: Text((articleEntity.like ?? 0).toString()),
                    onTap: () => _like(articleEntity.id ?? ''),
                  ),
                  Spacer(),
                  Icon(
                    Icons.more_horiz,
                    color: CommonColor.color99,
                    size: 20,
                  ),
                  SizedBox(
                    width: 6,
                  ),
                ],
              )
            ],
          ),
        ),
        onTap: () {
          Get.to(ArticleDetail(articleEntity));
        },
      );
    }
  }

  _singleAD(String pos) {
    return InstaImageViewer(
      child: CachedNetworkImage(
        width: 68,
        height: 68,
        fit: BoxFit.cover,
        alignment: Alignment.topCenter,
        imageUrl: pos,
      ),
    );
  }

  Future<void> myAsyncRefreshFunction() async {
    _getArticle();
  }
}
